package com.example.roleplay.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;

/**
 * Spring配置类
 */
@Configuration
public class AppConfig implements WebMvcConfigurer {

    /**
     * ChatClient Bean配置
     */
    @Bean
    public ChatClient chatClient(ChatModel chatModel) {
        return ChatClient.builder(chatModel).build();
    }

    /**
     * 知识库专用ChatClient Bean配置
     */
    @Bean("knowledgeBaseChatClient")
    public ChatClient knowledgeBaseChatClient(ChatModel chatModel) {
        return ChatClient.builder(chatModel)
                .defaultSystem("你是一个专业的AI助手，请基于提供的上下文信息准确回答用户问题。")
                .build();
    }

    /**
     * PgVector向量存储配置
     * 当自动配置失效时手动配置VectorStore
     */
    @Bean
    public VectorStore vectorStore(
            DataSource dataSource, 
            EmbeddingModel embeddingModel,
            @Value("${spring.ai.vectorstore.pgvector.table-name:vector_store}") String tableName,
            @Value("${spring.ai.vectorstore.pgvector.schema-name:public}") String schemaName,
            @Value("${spring.ai.vectorstore.pgvector.initialize-schema:true}") boolean initializeSchema) {
        
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
        return PgVectorStore.builder(jdbcTemplate, embeddingModel)
                .schemaName(schemaName)
                .vectorTableName(tableName)
                .initializeSchema(initializeSchema)
                .build();
    }

    /**
     * RestTemplate Bean配置
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }



    /**
     * 静态资源处理器配置
     * 确保静态资源能够正确访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(0); // 开发环境禁用缓存
    }

    /**
     * CORS跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("*") // 允许所有来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true) // 允许携带凭证
                .maxAge(3600); // 预检请求缓存时间（秒）
    }
}